from django.db import models
from django.contrib.auth import get_user_model
from django.core.validators import MinValueValidator, MaxValueValidator

User = get_user_model()

class Department(models.Model):
    """科室模型"""
    name = models.CharField('科室名称', max_length=50, unique=True)
    icon = models.CharField('图标', max_length=10, default='🏥')
    description = models.TextField('科室描述', blank=True, null=True)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, verbose_name='父科室')
    sort_order = models.IntegerField('排序', default=0)
    is_active = models.BooleanField('是否启用', default=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'department'
        verbose_name = '科室'
        verbose_name_plural = '科室'
        ordering = ['sort_order', 'name']

    def __str__(self):
        return self.name

class Doctor(models.Model):
    """医生模型"""
    TITLE_CHOICES = [
        ('resident', '住院医师'),
        ('attending', '主治医师'),
        ('associate', '副主任医师'),
        ('chief', '主任医师'),
        ('professor', '教授'),
    ]

    STATUS_CHOICES = [
        ('active', '在职'),
        ('inactive', '停诊'),
        ('vacation', '休假'),
    ]

    name = models.CharField('医生姓名', max_length=50)
    title = models.CharField('职称', max_length=20, choices=TITLE_CHOICES)
    department = models.ForeignKey(Department, on_delete=models.CASCADE, verbose_name='所属科室')
    avatar = models.URLField('头像', max_length=500, blank=True, null=True)
    introduction = models.TextField('医生简介', blank=True, null=True)
    specialties = models.JSONField('擅长领域', default=list, blank=True)
    experience_years = models.IntegerField('从业年限', default=0)
    education = models.CharField('学历', max_length=100, blank=True, null=True)
    hospital = models.CharField('所属医院', max_length=200, blank=True, null=True)
    consultation_fee = models.DecimalField('咨询费用', max_digits=8, decimal_places=2, default=0)
    rating = models.FloatField('评分', default=0.0, validators=[MinValueValidator(0), MaxValueValidator(5)])
    rating_count = models.IntegerField('评价人数', default=0)
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='active')
    is_featured = models.BooleanField('是否推荐', default=False)
    license_number = models.CharField('执业证书号', max_length=100, blank=True, null=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'doctor'
        verbose_name = '医生'
        verbose_name_plural = '医生'
        ordering = ['-is_featured', '-rating', 'name']

    def __str__(self):
        return f"{self.name} - {self.get_title_display()}"

class Banner(models.Model):
    """轮播图模型"""
    title = models.CharField('标题', max_length=100)
    subtitle = models.CharField('副标题', max_length=200, blank=True, null=True)
    description = models.TextField('描述', blank=True, null=True)
    image = models.URLField('图片URL', max_length=500)
    link = models.URLField('链接地址', max_length=500, blank=True, null=True)
    sort_order = models.IntegerField('排序', default=0)
    is_active = models.BooleanField('是否启用', default=True)
    start_time = models.DateTimeField('开始时间', null=True, blank=True)
    end_time = models.DateTimeField('结束时间', null=True, blank=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'banner'
        verbose_name = '轮播图'
        verbose_name_plural = '轮播图'
        ordering = ['sort_order', '-created_at']

    def __str__(self):
        return self.title

class HealthService(models.Model):
    """健康服务模型"""
    name = models.CharField('服务名称', max_length=100)
    description = models.TextField('服务描述', blank=True, null=True)
    icon = models.CharField('图标', max_length=10, default='🏥')
    features = models.JSONField('服务特色', default=list, blank=True)
    link = models.URLField('链接地址', max_length=500, blank=True, null=True)
    sort_order = models.IntegerField('排序', default=0)
    is_active = models.BooleanField('是否启用', default=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'health_service'
        verbose_name = '健康服务'
        verbose_name_plural = '健康服务'
        ordering = ['sort_order', 'name']

    def __str__(self):
        return self.name

class Appointment(models.Model):
    """预约模型"""
    STATUS_CHOICES = [
        ('pending', '待确认'),
        ('confirmed', '已确认'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
        ('no_show', '未到诊'),
    ]

    APPOINTMENT_TYPE_CHOICES = [
        ('online', '在线咨询'),
        ('offline', '线下就诊'),
        ('video', '视频问诊'),
        ('phone', '电话咨询'),
    ]

    appointment_no = models.CharField('预约号', max_length=50, unique=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='患者')
    doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE, verbose_name='医生')
    appointment_type = models.CharField('预约类型', max_length=20, choices=APPOINTMENT_TYPE_CHOICES)
    appointment_date = models.DateTimeField('预约时间')
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='pending')
    symptoms = models.TextField('症状描述', blank=True, null=True)
    medical_history = models.TextField('病史', blank=True, null=True)
    fee = models.DecimalField('费用', max_digits=8, decimal_places=2)
    remark = models.TextField('备注', blank=True, null=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'appointment'
        verbose_name = '预约'
        verbose_name_plural = '预约'
        ordering = ['-created_at']

    def __str__(self):
        return f"预约 {self.appointment_no}"

class Consultation(models.Model):
    """咨询记录模型"""
    STATUS_CHOICES = [
        ('ongoing', '进行中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    ]

    consultation_no = models.CharField('咨询号', max_length=50, unique=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='患者')
    doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE, verbose_name='医生')
    appointment = models.ForeignKey(Appointment, on_delete=models.CASCADE, null=True, blank=True, verbose_name='关联预约')
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='ongoing')
    start_time = models.DateTimeField('开始时间')
    end_time = models.DateTimeField('结束时间', null=True, blank=True)
    diagnosis = models.TextField('诊断结果', blank=True, null=True)
    prescription = models.TextField('处方', blank=True, null=True)
    advice = models.TextField('医嘱', blank=True, null=True)
    fee = models.DecimalField('费用', max_digits=8, decimal_places=2)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'consultation'
        verbose_name = '咨询记录'
        verbose_name_plural = '咨询记录'
        ordering = ['-created_at']

    def __str__(self):
        return f"咨询 {self.consultation_no}"

class HealthRecord(models.Model):
    """健康档案模型"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    record_type = models.CharField('记录类型', max_length=50)  # 如：血压、血糖、体重等
    value = models.CharField('数值', max_length=100)
    unit = models.CharField('单位', max_length=20, blank=True, null=True)
    record_date = models.DateTimeField('记录时间')
    notes = models.TextField('备注', blank=True, null=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)

    class Meta:
        db_table = 'health_record'
        verbose_name = '健康档案'
        verbose_name_plural = '健康档案'
        ordering = ['-record_date']

    def __str__(self):
        return f"{self.user.username} - {self.record_type}"

class DoctorReview(models.Model):
    """医生评价模型"""
    RATING_CHOICES = [
        (1, '1星'),
        (2, '2星'),
        (3, '3星'),
        (4, '4星'),
        (5, '5星'),
    ]

    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='患者')
    doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE, verbose_name='医生')
    consultation = models.ForeignKey(Consultation, on_delete=models.CASCADE, verbose_name='咨询记录')
    rating = models.IntegerField('评分', choices=RATING_CHOICES)
    content = models.TextField('评价内容', blank=True, null=True)
    is_anonymous = models.BooleanField('是否匿名', default=False)
    created_at = models.DateTimeField('评价时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'doctor_review'
        verbose_name = '医生评价'
        verbose_name_plural = '医生评价'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.user.username} 对 {self.doctor.name} 的评价"

class MedicalArticle(models.Model):
    """医疗文章模型"""
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('published', '已发布'),
        ('archived', '已归档'),
    ]

    title = models.CharField('文章标题', max_length=200)
    content = models.TextField('文章内容')
    summary = models.TextField('文章摘要', blank=True, null=True)
    author = models.ForeignKey(Doctor, on_delete=models.CASCADE, verbose_name='作者')
    category = models.CharField('分类', max_length=100, blank=True, null=True)
    tags = models.JSONField('标签', default=list, blank=True)
    cover_image = models.URLField('封面图片', max_length=500, blank=True, null=True)
    view_count = models.IntegerField('浏览次数', default=0)
    like_count = models.IntegerField('点赞次数', default=0)
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='draft')
    is_featured = models.BooleanField('是否推荐', default=False)
    published_at = models.DateTimeField('发布时间', null=True, blank=True)
    created_at = models.DateTimeField('创建时间', auto_now_add=True)
    updated_at = models.DateTimeField('更新时间', auto_now=True)

    class Meta:
        db_table = 'medical_article'
        verbose_name = '医疗文章'
        verbose_name_plural = '医疗文章'
        ordering = ['-published_at', '-created_at']

    def __str__(self):
        return self.title
